package com.chen.controller;

import cn.hutool.core.util.ObjectUtil;
import com.chen.bean.entity.UserEntity;
import com.chen.bean.enums.ResultCode;
import com.chen.bean.result.RefreshTokenResult;
import com.chen.bean.result.Result;
import com.chen.bean.vo.WxLoginRequest;
import com.chen.bean.vo.WxUserInfo;
import com.chen.interceptor.WxLoginInterceptor;
import com.chen.service.UserService;
import com.chen.util.JsonMapper;
import com.chen.util.JwtHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 微信用户登录接口
 */
@RestController
@RequestMapping("/wx")
@Slf4j
public class WxLoginController {
    @Autowired
    private UserService userService;

    /**
     * 微信登录
     */
    @PostMapping("/login")
    public Result<WxUserInfo> login(@RequestBody WxLoginRequest request) throws Exception {
        if (ObjectUtil.isNull(request) || StringUtils.isBlank(request.getCode())){
            return Result.fail(ResultCode.ERROR_PARAMS);
        }
        WxUserInfo userInfo = userService.loginByWx(request);
        return Result.success(userInfo);
    }


    /**
     * 刷新token
     */
    @GetMapping("/refresh-token")
    public Result<RefreshTokenResult> refreshToken(){
        log.info("刷新token执行");
        UserEntity currentUser = WxLoginInterceptor.getCurrentUser();
        String token = JwtHelper.createToken(JsonMapper.toJson(currentUser));
        RefreshTokenResult result = new RefreshTokenResult();
        result.setToken(token);
        result.setExpiresIn((long) (2 * 60 * 60));
        return Result.success(result);
    }


}
